//
//  XQOrderMenuView.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit

class XQOrderMenuView: UIView {
    
    private lazy var dataSource : Array = ["Applying","Not yet repaid","Repayed"]
    
    private lazy var buttons : [UIButton] = []
    
    public var menuHandle: ((Int) -> Void)?
    
    public lazy var selectIndex : Int = 0 {
        didSet {
            for (index,button) in buttons.enumerated() {
                button.setTitleColor(index == selectIndex ? .white : .xq_black, for: .normal)
                button.backgroundColor = index == selectIndex ? .mainTextColor : .white
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
        self.selectIndex = 0
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
        self.selectIndex = 0
    }
    
    private func makeUI() {
        let width = (Int(UIDevice.xq_width()) - 16 * 2) / dataSource.count
        let height = 34
        
        buttons.removeAll()
        
        for (index, value) in dataSource.enumerated() {
            let btn = UIButton(type: .custom)
            btn.setTitle(value, for: .normal)
            btn.setTitleColor(.xq_black, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12,weight: .medium)
            btn.layer.cornerRadius = 17
            btn.tag = index
            btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
            self.addSubview(btn)
            
            btn.snp.makeConstraints { make in
                if index == 0 {
                    make.left.equalTo(16)
                }else {
                    make.left.equalTo(buttons[index - 1].snp.right)
                }
                make.height.equalTo(height)
                make.top.equalToSuperview()
                make.width.equalTo(width)
            }
            
            buttons.append(btn)
        }
    }
    
    @objc private func btnClick(_ sender: UIButton) {
        self.selectIndex = sender.tag
        menuHandle?(sender.tag)
    }
}
